package org.yu.api.multiblock;

import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import org.yu.api.util.ITickable;

import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
public abstract class ControlBlockEntity extends BlockEntity implements ITickable {
    private boolean isFormed = false;
    private FormingToolHolder formingToolHolder;

    public ControlBlockEntity(BlockEntityType<?> pType, BlockPos pWorldPosition, BlockState pBlockState) {
        super(pType, pWorldPosition, pBlockState);
    }

    public FormingToolHolder getFormingToolHolder() {
        return formingToolHolder;
    }

    public void setFormingToolHolder(FormingToolHolder formingToolHolder) {
        this.formingToolHolder = formingToolHolder;
    }

    public boolean isFormed() {
        return isFormed;
    }

    @Override
    public void tick() {
        if (isFormed) formedTick();
    }

    /**
     * 多方块成形后的tick
     */
    public abstract void formedTick();

    @Override
    protected void saveAdditional(CompoundTag pTag) {
        super.saveAdditional(pTag);
        pTag.putBoolean("IsFormed", isFormed);
    }

    @Override
    public void load(CompoundTag pTag) {
        super.load(pTag);
    }

    public boolean tryFormMultiBlock(ItemStack itemStack) {
        if (formingToolHolder == null) return false;
        boolean successd = formingToolHolder.usingTool(itemStack);
        if (successd) {

        }
        return successd;
    }

    /**
     * 当实体方块数据更新后调用
     */
    public void markDirty() {
        if (level instanceof ServerLevel serverLevel) serverLevel.getChunk(getBlockPos()).setUnsaved(true);
    }
}
